import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, getUserInfo, logout } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)

  /**
   * @description 登录
   * @param {Object} loginForm - 登录表单数据
   * @returns {Promise}
   */
  const userLogin = async (loginForm) => {
    try {
      const { code, data, token: newToken, message} = await login(loginForm)
      if (code === 401) {
        ElMessage.error(message || "认证失败")
        window.open(data)
        return
      }
      // token.value = newToken
      // localStorage.setItem('token', newToken)
    } catch (error) {
      throw error
    }
  }

  /**
   * @description 获取用户信息
   * @returns {Promise}
   */
  const fetchUserInfo = async () => {
    try {
      const data = await getUserInfo()
      userInfo.value = data
      return data
    } catch (error) {
      throw error
    }
  }

  /**
   * @description 登出
   */
  const userLogout = async (id) => {
    try {
      await logout(id)
    } catch (error) {
      console.error('登出失败', error)
    } finally {
      token.value = ''
      userInfo.value = null
      localStorage.removeItem('token')
    }
  }

  return {
    token,
    userInfo,
    login: userLogin,
    getUserInfo: fetchUserInfo,
    logout: userLogout
  }
}) 